<?php
class GuestsController extends UsersAppController
{
	var $name = 'Guests';
	var $components = array('Session', 'Email', 'RequestHandler', 'Cookie');
	var $helpers = array('Html','Form');
	
	function add() 
	{
		$guestId = null;
		if($this->Session->read('Auth.Guest.id'))
			$guestId =  $this->Session->read('Auth.Guest.id');
		if($guestId &&  Cr('User.Guest.allowGuestUpdate') == false)
		{
			$this->redirect($this->referer());
		}
		$userExist = false;
		if($this->data)
		{
			if($guestId)
			{
				$this->data['Guest']['id'] = $guestId;
			}			
			if($this->Guest->save($this->data))
			{
				$this->login($this->Guest->id);
				callHooks('AfterGuestAdd','.+',$this);
				$this->Session->write('Your email has been saved');
				$this->redirect($this->referer());
			}else
			{
				if(isset($this->Guest->validationErrors['exist_as_user']))
				{
					$userExist = true;
					$this->errorMsg(__("User with this email exists in our database.Please login to continue"));
				}else{
					$this->errorMsg(__("There was error is saving.Please see the errors below"));
				}
			}
		}
		$this->set('userExist',$userExist);

	}	
	
	function validate($code = null)
	{
		if($this->Session->read('Auth.User.id'))
			$this->redirect();
		if(!$code)
			$this->redirect($this->referer());
		$guest = $this->Guest->find('first',array('conditions'=>array('validateCode'=>$code),'recursive'=>-1));
		if($guest)
		{
			$this->Guest->id = $guest['Guest']['id'];
			$this->Guest->saveField('email_verified',1);
			$this->loginGuest($guest['Guest']['id']);
			callHooks('AfterGuestEmailVerfied','.+',$this);
			$this->successMsg(__("Your emil has been verified"));
			$this->redirect('/');
		}
		$this->redirect('/');
	}
	
	private function login($id)
	{
		$guest =  $this->Guest->findById($id);
		$this->Session->write('Auth.model', 'Guest');
		$this->Session->write('Auth.Guest', $guest ['Guest']);
	}	

}
?>